$(function () {
  $(".tab4").click(function () {
    $('#install_button').attr('disabled',true);
    displayProSetting();
    preInstall();
  });
  
  $("#install_button").click(function () {
      $('#install_button').attr('disabled',true);//click安装按钮后disabled
      install();
  });
  $("#waiting").hide();
});

function preInstall() {
  var toBePromotedNum = getToBePromotedNum();
  var validatePass = validateToBePromoteMaxNum(toBePromotedNum);
  if(!validatePass){
    return;
  }
  
  var intelligence_nums = $("#num_1").val();
  var is_intell_close = $('input[name=intell_switch]:checked').val();
  if(is_intell_close == 'intell_off'){
    intelligence_nums = 0;
  }
  validatePass = validateToBePromoteMinNum(toBePromotedNum,intelligence_nums);
  if(!validatePass){
    return;
  }
  
  var installSetting = $('input[name=promot]:checked').val();
  var toPromoteNum = getToPromoteNum();
  var sellerCats = '';
  $("input[name=seller_cats_promote]:checked").each(function(){
    sellerCats+=$(this).val();
  });
  validatePass = validateToPromoteNum(installSetting,sellerCats,toPromoteNum);
  if(!validatePass){
    return;
  }
  validatePass= validateStyleInfo();
  if(!validatePass){
    return;
  }
  
  var params = {
      "ipro.install_setting":installSetting,
      "ipro.seller_cats":sellerCats,
      "ipro.to_promote_num":toPromoteNum,
      "ipro.install_place":$('input[name=install_place]:checked').val()
  };
 $.post("preInstall.action", params, processPreResponse, "json");
}

function validateToBePromoteMaxNum(toBePromotedNum){
  var version_no = $("#version_no").val();
  var maxPromoteNum = 20;
  if(version_no==3){
     maxPromoteNum = 80;
  }else if(version_no==2){
     maxPromoteNum = 30;
  }else{
     maxPromoteNum = 10;
  }
  if(toBePromotedNum > maxPromoteNum){
    var text ="第1步中选择了太多宝贝，您的版本最多只支持";
    text+= maxPromoteNum+"个，请<a target='_blank' style='text-decoration:underline;color:blue' href='http://www.ambitor.net/notice_detail.action?article.article_id=2'>升级为更高版本</a>";
    $('#install_reminder').html(text);
    $('#install_button').attr('disabled',true);
    return false;
  }
  return true;
}

function validateToBePromoteMinNum(toBePromotedNum,intelligence_nums){
  if(parseInt(toBePromotedNum)+parseInt(intelligence_nums) ===0){
    var text ="请在第1步中选择您要推广的宝贝。";
    $('#install_reminder').html(text);
    $('#install_button').attr('disabled',true);
    return false;
  }
  return true;
}

function validateToPromoteNum(installSetting,sellerCats,toPromoteNum){
  var isPass = true;
  var text = '';
  if(installSetting === 'custom' && toPromoteNum===0){
    text ="您想把推广模块安装到哪些宝贝上？请在第3步中选择。";
    isPass =false;
  }else if(installSetting ==='someCategory' && sellerCats ===''){
    text ="您想把推广模块安装到哪些类别的宝贝上？请在第3步中选择。";
    isPass =false;
  }
  if(!isPass){
    $('#install_reminder').html(text);
    $('#install_button').attr('disabled',true);
  }
  return isPass;
}

function validateStyleInfo(){
  var isPass = true;
  var text = '';
  var rowid = $("#styleTable").getGridParam("selrow");
  if(rowid === null){
  	text ="请在第2步中选择或新建样式";
    isPass =false;
  }
  if(!isPass){
    $('#install_reminder').html(text);
    $('#install_button').attr('disabled',true);
  }
	return isPass;
}

function processPreResponse(data) {
  var code = data.result.code;
  var text = data.result.msg;
  $('#install_reminder').html(text);
  if(Number(code)>0){
    $('#install_button').attr('disabled',false);//成功的话显示安装按钮
  }else{
    $('#install_button').attr('disabled',true);
  }
}

function install() {
  var bePromotedItemIds = getBePromotedItemIds();
  var toPromoteItemIds = getToPromoteItemIds();
  
  
  var intelligence_labels = $("#intelligence_label_1").val();
  var intelligence_nums = $("#num_1").val();
  
  var installSetting = $('input[name=promot]:checked').val();
  var sellerCats = '';
  if(installSetting =='someCategory'){
    $("input[name=seller_cats_promote]:checked").each(function(){
      sellerCats+=$(this).val();
      sellerCats+= ',';
    });  
    sellerCats = sellerCats.slice(0,sellerCats.length-1);
  }

  var rowid = $("#styleTable").getGridParam("selrow");
  var ret = $("#styleTable").jqGrid("getRowData", rowid);
  if(ret.STYLE_ID == null || ret.STYLE_ID == ""){
  	alert("请到第2步中选择或新建样式");
  	return;
  }
  var params = {
    "ipro.is_intell_close":$('input[name=intell_switch]:checked').val(),
    "ipro.intell_labels":intelligence_labels,
    "ipro.intell_nums":intelligence_nums,
    "ipro.intell_frequency":$("#frequency").val(),
    "ipro.promote_radio":installSetting,
    "ipro.install_place":$('input[name=install_place]:checked').val(),
    "ipro.install_cids":sellerCats,
    "ipro.be_promoted_iids":bePromotedItemIds,
    "ipro.to_promote_iids":toPromoteItemIds,
  	"userStyle.STYLE_ID":ret.STYLE_ID
  };
  $("#waiting").show();
  $.post("install.action", params, processInstallResponse, "json");
}

function processInstallResponse(data,status){
  $("#waiting").hide();
  var code = data.result.code;
  var text = data.result.msg;
  if(Number(code)>0){
    text="预计安装在15分钟左右完成,你可以到[安装日志]页面查看安装情况!";
    alert(text);
    location.href=$('#query_install_log_loaction').val();
    resetContext();
  }else{
    alert(text);
  }
}

function resetContext(){
   $('#promot_resp').html("");
   $("#sortable_step1_2").html("");
   $('#step3_ipro_module').html("");
   try{
    $("#gridTable").jqGrid("resetSelection");
    $("#promot_gridTable").jqGrid("resetSelection");
   }catch(e){
   }
}

function getBePromotedItemIds(){
  var iids = "";
  $('#sortable_step1_2 div').each(function(){
    iids += $(this).attr('id')+",";
  });
  iids = iids.slice(0,iids.length-1);
  return iids;
}

function getToPromoteItemIds(){
  var iids = "";
  $('#promot_resp div').each(function(){
    var id = $(this).attr('id')+",";
    id = id.slice(4);
    iids += id;
  });
  iids = iids.slice(0,iids.length-1);
  return iids;
}

function getToPromoteNum(){
  var num = 0;
  $('#promot_resp div').each(function(){
    num++;
  });
  return num;
}

function getToBePromotedNum(){
  var num = 0;
  $('#sortable_step1_2 li').each(function(){
    num++;
  });
  return num;
}


function displayProSetting(){
  $("#pro_setting_table").jqGrid('clearGridData');
  $("#pro_setting_table").jqGrid({
    datatype: "local",
    height: 50,
    width: 750,
    colNames:['哪些宝贝来安装','动态更换宝贝','静态推广宝贝', '动态宝贝更换频率'],
    colModel:[
              {name:'install_setting',index:'install_setting', width:100},
              {name:'intell_label',index:'intell_label', width:100},  
              {name:'static_num',index:'static_num', width:100},
              {name:'frequency',index:'frequency', width:100}
             ],
    caption: "本次安装情况"
  });
  
  var install_setting = $('input[name=promot]:checked').val();
  var intelligence_num = $("#num_1").val();
  var intell_label = $("#intelligence_label_1").val();
  
  var is_intell_close = $('input[name=intell_switch]:checked').val();
  var frequency =$("#frequency").val(); 
  if(is_intell_close == 'intell_off'){
    intelligence_num = 0;
    intell_label = '0';
    frequency = 0;
  }
  
  if(frequency === 0){
    frequency = '不更新';
  }else{
    frequency = frequency + '天一次';
  }
  
  var intell_label_name = '';
  if(intelligence_num === 0){
    intell_label_name ='没有';
  }else{
    intell_label_name = intelligence_num+"个";
  }
  
  var static_num = getToBePromotedNum();
  var mydata=[{install_setting:getInstallSettingName(install_setting),
               intell_label:getIntellLableName(intell_label)+intell_label_name,
               static_num:static_num+"个",
               frequency:frequency
              }
             ];
  $("#pro_setting_table").jqGrid('addRowData',1,mydata); 
  var ids = $("#pro_setting_table").getDataIDs(); 
  $("#pro_setting_table").setRowData(ids[0],false, {height: 30}); 
}

function getInstallSettingName(installSetting) {
  if(installSetting == 'all'){
    return '所有宝贝';
  }
  else if(installSetting =='onSale'){
    return '出售中的宝贝';
  }else if(installSetting =='someCategory'){
    return '指定类别';
  }else if(installSetting =='custom'){
    return '自定义选择';
  }
}

function getIntellLableName(intell_label){
  if(intell_label <= 0){
    return '';
  }
  var labels = {};
  labels[1]="最近上架的宝贝";
  labels[2]="本店销量最高的宝贝";
  labels[3]="本店销量最低的宝贝";
  labels[4]="本店流量最高的宝贝";
  labels[5]="本店流量最低的宝贝";
  labels[11]="最近编辑过的宝贝";
  labels[12]="本店价格最高的宝贝";
  labels[13]="本店价格最低的宝贝";
  labels[15]="同类随机推荐宝贝";
  labels[16]="同类价格高的宝贝";
  labels[17]="同类价格低的宝贝";
  var result = labels[intell_label];
  if(result === null){
    result = '未知规则';
  }
  return '['+result+']';
}
